const http = require("http");
const fs = require("fs");
const url = require("url");

http.createServer(server).listen(3000);

function server(req, res){
    res.writeHead(200, {
        // "Content-Type": "application/json;charset=utf-8",
        "access-control-allow-origin":"*"
    })

    const path = url.parse(req.url).pathname;
    // 1. 获取集团：http://localhost:3000/api/group
    // 2.1. 获取集团介绍：http://localhost:3000/api/group_detail?id=01
    // 2.2. 获取集团对应子品牌：http://localhost:3000/api/brand?id=01
    // 3. 获取集团对应子品牌介绍：http://localhost:3000/api/brand_detail?id=001
    if(path.includes("/api/brand_detail")){
        brandDetail(req, res);
    }else if(path.includes("/api/group_detail")){
        groupDetail(req, res);
    }else if(path.includes("/api/group")){
        group(req, res);
    }else if(path.includes("/api/brand")){
        brand(req, res);
    }else if(path === "/"){
        def(req, res);
    }else{
        error(req,res);
    }
}

function group(req, res){
    const data = fs.readFileSync("./data/group.json", "utf-8");
    res.write("a"+JSON.stringify(JSON.parse(data)));
    res.end();
}

function def(req, res){
    const data = fs.readFileSync("./api.md", "utf-8");
    res.write(data);
    res.end();
}

function groupDetail(req, res){
    const query = url.parse(req.url, true).query;
    const data = fs.readFileSync("./data/group_detail.json", "utf-8");
    const arr = JSON.parse(data).filter(val=>val.id === query.id)[0] || [];
    const d = JSON.stringify(arr);
    res.write(d);
    res.end();
}

function brand(req, res){
    const query = url.parse(req.url, true).query;
    const data = fs.readFileSync("./data/brand.json", "utf-8");
    const arr = JSON.parse(data).filter(val=>val.id === query.id)[0] || [];
    const child = arr.children || [];
    const d = JSON.stringify(child);
    res.write(d);
    res.end();
}

function brandDetail(req, res){
    const query = url.parse(req.url, true).query;
    const data = fs.readFileSync("./data/brand_detail.json", "utf-8");
    const arr = JSON.parse(data).filter(val=>val.title == query.title)[0] || [];
    const d = JSON.stringify(arr);
    res.write(d);
    res.end();
}

function error(req, res){
    res.write(`{ error: "接口不存在" }`)
    res.end();
}
